package com.zhf.server.impl;

import com.zhf.model.Question;
import com.zhf.model.QuestionImportVo;
import com.zhf.model.QuestionMessage;
import com.zhf.model.QuestionUpdVo;
import com.zhf.server.ExamQuestionService;
import com.zhf.server.ServerDao;

import java.util.List;
import java.util.stream.Collectors;

public class ExamQuestionServiceImpl implements ExamQuestionService {
    ServerDao serverDao;
    public ExamQuestionServiceImpl(ServerDao serverDao){
        this.serverDao = serverDao;
    }

    @Override
    public QuestionMessage addExamQuestion(Question question) {
        QuestionMessage questionMessage = serverDao.addQuestion(question);
        return questionMessage;
    }

    @Override
    public QuestionMessage deleteExamQuestion(Question question) {
        QuestionMessage questionMessage = selectQuestion(question);
        if("fail".equals(questionMessage.getMessage())){
            return  questionMessage;
        }
        else{
            questionMessage = serverDao.deleteQuestion(question);
        }
        return questionMessage;
    }

    @Override
    public QuestionUpdVo updateQuestion(QuestionUpdVo questionUpdVo) {
        QuestionUpdVo questionUpdVo1 = new QuestionUpdVo();
        String originQuestionName = questionUpdVo.getOriginQuestionName();
        Question question = new Question();
        question.setQuestionName(originQuestionName);
        QuestionMessage questionMessage = selectQuestion(question);
        if("fail".equals(questionMessage.getMessage())){
            QuestionMessage questionMessage1 = new QuestionMessage();
            questionMessage1.setMessage("fail");
            questionMessage1.setQuestion(questionUpdVo.getQuestionMessage().getQuestion());
            questionUpdVo1.setQuestionMessage(questionMessage1);
            questionUpdVo1.setOriginQuestionName(originQuestionName);
            return questionUpdVo1;
        }
        else{
            questionUpdVo1 = serverDao.updateQuestion(questionUpdVo);
        }
        return questionUpdVo1;
    }

    @Override
    public QuestionMessage selectQuestion(Question question) {
        QuestionMessage questionMessage = serverDao.selectQuestion(question);
        return questionMessage;
    }

    @Override
    public QuestionImportVo importQuestion(List<Question> questions) {
        // 校验导入的考题中是否有重复的考题
        List<String> collect = questions.stream().map(Question::getQuestionName).distinct().collect(Collectors.toList());
        if(collect.size() < questions.size()){
            System.out.println("导入考题中有重复的考题！");
            return new QuestionImportVo(questions, "fail");
        }
        QuestionImportVo questionImportVo = serverDao.importQuestion(questions);
        return questionImportVo;
    }
}
